//
//  StatisticsHomeController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/23.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh

class StatisticsHomeController: WarningBaseController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            _tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
//            _tableView.register(ProjectCell.self, forCellReuseIdentifier: "\(ProjectCell.self)")
            _tableView.register(UINib.init(nibName: "ProjectNormalCell", bundle: nil), forCellReuseIdentifier: "ProjectNormalCell")
            _tableView.register(ProjectNoDataCell.self, forCellReuseIdentifier: "\(ProjectNoDataCell.self)")
            _tableView.register(RecordDateCell.self, forCellReuseIdentifier: "\(RecordDateCell.self)")
            _tableView.register(UINib.init(nibName: "OvertimeSwitchCell", bundle: nil), forCellReuseIdentifier: "switch")
            return _tableView
        }
    }
    
    var projectModel: ProjectModel?//当前项目
    var displayDate = Date() //当前显示的日期
    var recordSupplyLists: [RecordSupply]?//当月签到记录,日历上
    
    var workingMonth: StatisticsWorkingModel? // 一个月的出工统计
    var workingTotal: StatisticsWorkingModel?   //全部出工统计
    var isOvertime:Bool? = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        WWUser.sharedInstance.ensureCertificationStatus(self)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "统计"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        NotificationCenter.default.addObserver(self, selector: #selector(doNotifcationAction), name: NSNotification.Name.init(kNotificationSelectedProjectChanged), object: nil)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "记录", style: .done, target: self, action: #selector(doSupplyAction))
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
        
        
        
        self.setupViews()
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "点击", style: .done, target: self, action: #selector(doRightAction))
        
        let tableHeader = MJRefreshNormalHeader { [unowned self] in
            self.updateData()
        }
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        
        self.getProjectDate()
    }
    @objc fileprivate func doSupplyAction(){
        let vc = SupplyAndOvertimeViewController(nibName: "SupplyAndOvertimeViewController", bundle: nil)
        vc.projectModel = self.projectModel
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func setupViews() {
        self.baseView.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.baseView)
        }
    }
    
    func doRightAction() {

        
    }
    
    @objc func doNotifcationAction() {
        self.getProjectDate()
    }
    
    func getProjectDate() {
        ProjectModel.projectList(pageIndex: 1, pageSize: 1) { (response) in
            if response.success {
                if let values = response.value, values.count > 0 {
                    self.projectModel = values[0]
                }
                else {
                    self.projectModel = nil
                }
        self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
                
            }
            else {
                WWError("数据获取失败")
            }
            self.updateData()
        }

    }
    
    func updateData() {
        guard let model = self.projectModel,let demandBaseMigrantWorkerID = model.demandBaseMigrantWorkerID  else {
           
            self.tableView.mj_header.endRefreshing()
            return
        }
        self.getRecordItemOfMonth(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)//月历上用
        self.getStatisticsWorkingOfMonth(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)//一个月的出工情况
        self.getStatisticsWorkingTotal(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)//全部出工情况
    }
    
    //
    /// 获取指定月一个的签到情况
    ///
    /// - Parameters:
    ///   - demandBaseMigrantWorkerID:
    ///   - method: nil获取月历上显示的内容
    fileprivate func getRecordItemOfMonth(demandBaseMigrantWorkerID: String) {
        let firstDay = displayDate.startOfMonth()
        let lastDay = displayDate.endOfMonth()
        
        let firstDayString = dateTimeToString(date: firstDay)
        let lastDayString = dateTimeToString(date: lastDay)
        
        RecordSupply.getRecordStatisticInMonth(workerId: demandBaseMigrantWorkerID, startTime: firstDayString, lastTime: lastDayString) { (response) in
            if response.success {
                self.recordSupplyLists = response.value
                self.tableView.reloadData()
            }
            else {
                WWError(response.message)
            }
            self.tableView.mj_header.endRefreshing()
        }
    }
    
    //一个月的出工情况
    fileprivate func getStatisticsWorkingOfMonth(demandBaseMigrantWorkerID: String) {
        let firstDay = displayDate.startOfMonth()
        let lastDay = displayDate.endOfMonth()
        
        let firstDayString = dateTimeToString(date: firstDay)
        let lastDayString = dateTimeToString(date: lastDay)
        
        StatisticsWorkingModel.getStatisticsWorkingAMonth(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, startTime: firstDayString, lastTime: lastDayString) { (response) in
            if response.success {
                self.workingMonth = response.value
                self.tableView.reloadSections(IndexSet.init(integer: 3), with: .automatic)
            }
            else {
                WWError(response.message)
                self.workingMonth = nil
            }
        }
    }
    
    //所有的出工情况
    fileprivate func getStatisticsWorkingTotal(demandBaseMigrantWorkerID: String) {
        
        StatisticsWorkingModel.getStatisticsWorkingTotal(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID) { (response) in
            if response.success {
                self.workingTotal = response.value
                
            }
            else {
                WWError(response.message)
                self.workingTotal = nil
            }
            self.tableView.reloadSections(IndexSet.init(integer: 3), with: .automatic)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.init(kNotificationSelectedProjectChanged), object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension StatisticsHomeController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 3 {
            return 4
        }
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat([100 + 25,40, 400, 40][indexPath.section])
    }
    
    @objc fileprivate func overtimeSwitchClick(_ state:UISwitch){
        if state.isOn == true {
            self.isOvertime = true
        }else{
           self.isOvertime = false
        }
       self.updateData()
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            if self.projectModel == nil {
                let cell = getCell(tableView, cell: ProjectNoDataCell.self, indexPath: indexPath)
                return cell
            }
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(ProjectNormalCell.self)", for: indexPath) as! ProjectNormalCell
            cell.accessoryType = .disclosureIndicator
            if let model = self.projectModel {
                cell.bind(model)
            }
            return cell
        }else if indexPath.section == 1{
            let cell : OvertimeSwitchCell = tableView.dequeueReusableCell(withIdentifier: "switch") as! OvertimeSwitchCell
            cell.overtimeSwitch.addTarget(self, action: #selector(overtimeSwitchClick(_:)), for: .valueChanged)
            cell.overtimeSwitch.setOn(self.isOvertime!, animated: true)
            return cell
        }else if indexPath.section == 2 {//日期选择
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(RecordDateCell.self)", for: indexPath) as! RecordDateCell
            cell.recordSupplyLists = self.recordSupplyLists
            cell.currentMonthChangeHandler = {[unowned self](currentDate) in
                self.displayDate = currentDate
                self.tableView.mj_header.beginRefreshing()
            }
            cell.isOvertime = self.isOvertime
            cell.selectDateHandler = {(date) in
                //let vc = RecordSupplyDisplayController()
                let vc = MemorandumListViewController(nibName: "MemorandumListViewController", bundle: nil)
                guard let model = self.projectModel else {
                    WWError("请先选择项目")
                    return
                }
                
                vc.selectDate = date
                vc.projectModel = model
                vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            }
            
            return cell
        }
        else {//出工统计
//            let cell = tableView.dequeueReusableCell(withIdentifier: "\(UITableViewCell.self)", for: indexPath)
            let cell = UITableViewCell.init(style: .value1, reuseIdentifier: "\(UITableViewCell.self)")
            
            if self.projectModel?.workDayType == 2{
                cell.textLabel?.text = ["项目总出工天数", "项目总出工工时","本月出工天数", "本月开工工时"][indexPath.row]
            }else{
                cell.textLabel?.text = ["项目总出工天数", "总工数","本月开工天数", "本月工数"][indexPath.row]
            }
            cell.textLabel?.font = wwFont_Medium(16)
            cell.textLabel?.textColor = UIColor.mg_lightGray
            cell.detailTextLabel?.textColor = UIColor.black
            cell.detailTextLabel?.font = wwFont_Regular(16)
            
            if indexPath.row < 2 {
                
                if self.projectModel?.workDayType == 2{
                    if let model = self.workingTotal {
                        cell.detailTextLabel?.text = [model.workingDays + "天", model.workingHours + "小时"][indexPath.row]
                    }
                    else {
                        cell.detailTextLabel?.text = ["0天", "0小时"][indexPath.row]
                    }
                    
                    
                }else{
                    if let model = self.workingTotal {
                        cell.detailTextLabel?.text = [model.workingDays + "天", model.workedDays + "工"][indexPath.row]
                    }
                    else {
                        cell.detailTextLabel?.text = ["0天", "0工"][indexPath.row]
                    }
                    
                }
            }
            else {
                if self.projectModel?.workDayType == 2{
                    if let modelMonth = self.workingMonth {
                        cell.detailTextLabel?.text = [modelMonth.workingDays + "天", modelMonth.workingHours + "小时"][indexPath.row - 2]
                    }
                    else {
                        cell.detailTextLabel?.text = ["0天", "0小时"][indexPath.row - 2]
                    }
                }else{
                    if let modelMonth = self.workingMonth {
                        cell.detailTextLabel?.text = [modelMonth.workingDays + "天", modelMonth.workedDays + "工"][indexPath.row - 2]
                    }
                    else {
                        cell.detailTextLabel?.text = ["0天", "0工"][indexPath.row - 2]
                    }
                }
            }
            return cell
        }

    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            let vc = ProjectListViewController()
            vc.isChangeSelection = false
            vc.confirmSelection = {[unowned self](project) in
                self.projectModel = project
                self.tableView.mj_header.beginRefreshing()
                
                let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 2)) as! RecordDateCell
                cell.calendar.setCurrentPage(Date(), animated: false)
            }
            vc.hidesBottomBarWhenPushed = true
         self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return [0,10,1,10,30][section]
    }
    
}


























